package com.heima.wemedia.aspect;

import com.heima.common.redis.CacheService;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class DeleteCache {
    @Autowired
    CacheService cacheService;
    @Pointcut("execution(* com.heima.wemedia.service.WmMaterialService.uploadPicture(..))")
    public void uploadPicture() {}

    @Pointcut("execution(* com.heima.wemedia.service.WmMaterialService.delPicture(..))")
    public void delPicture() {}

    @Pointcut("execution(* com.heima.wemedia.service.WmNewsService.submitNews(..))")
    public void submitNews() {}

    @Pointcut("execution(* com.heima.wemedia.service.WmNewsService.downOrUp(..))")
    public void downOrUp() {}

    @Pointcut("execution(* com.heima.wemedia.service.WmChannelService.findAll(..))")
    public void findAll() {}
    /**
     * 在查询频道之前删除缓存
     */
    @After("findAll()")
    public void delWmChannel() {
        deleteCache("wm_channel");
    }
    /**
     * 在上传图片和删除图片之前删除缓存
     */
    @After("uploadPicture()||delPicture()")
    public void delWmMaterial() {
       deleteCache("wm_material");
    }
    /**
     * 在发布文章和上下架文章之前删除缓存
     */
    @After("submitNews()||downOrUp()")
    public void delWmNews() {
            deleteCache("wm_news");
    }

    /**
     * 延迟双删
     * @param keys 缓存key的前缀
     */
    @Async
    public void deleteCache(String keys){

        cacheService.delete(cacheService.scan(keys+"*"));
        try {
            Thread.sleep(500);
            cacheService.delete(cacheService.scan(keys+"*"));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
